package com.fansl.koala.quickdev.module.users.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fansl.koala.quickdev.common.bean.PageBean;
import com.fansl.koala.quickdev.common.constants.CommonConstants;
import com.fansl.koala.quickdev.common.enums.DeleteFlagEnum;
import com.fansl.koala.quickdev.common.utils.TreeUtil;
import com.fansl.koala.quickdev.module.users.entity.SysDept;
import com.fansl.koala.quickdev.module.users.mapper.SysDeptMapper;
import com.fansl.koala.quickdev.module.users.service.ISysDeptService;
import com.fansl.koala.quickdev.module.users.vo.DeptTreeVo;
import com.fansl.koala.quickdev.module.users.vo.SimpleTreeVo;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author fansl
 * @since 2020-03-20
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    /**
     * 分页查询组织树形数据
     *
     * @param pageParam 分页参数
     * @param sysDept   查询参数
     * @return 查询数据
     */
    @Override
    public PageBean<DeptTreeVo> pageDeptTree(PageBean<DeptTreeVo> pageParam, SysDept sysDept) {
        //分页参数
        Page<SysDept> queryPage = new Page<>();
        queryPage.setCurrent(pageParam.getPageNo());
        queryPage.setSize(pageParam.getPageSize());
        if (StrUtil.isNotBlank(pageParam.getSortOrder()) && StrUtil.isNotBlank(pageParam.getSortField())) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(pageParam.getSortOrder().equals(CommonConstants.PAGE_QUERY_ORDER_ASC));
            orderItem.setColumn(StrUtil.toUnderlineCase(pageParam.getSortField()));
            queryPage.setOrders(Collections.singletonList(orderItem));
        }
        SysDept queryParam = new SysDept();
        if(StrUtil.isNotBlank(sysDept.getName())){
            queryParam.setName(sysDept.getName());
        }
        LambdaQueryWrapper<SysDept> queryWrapper = Wrappers.lambdaQuery(queryParam);
        queryWrapper.eq(SysDept::getParentId, CommonConstants.TREE_PARENT_TOP_ID);

        Page<SysDept> result = page(queryPage, queryWrapper);

        List<Integer> parentIds = result.getRecords().stream()
                .map(SysDept::getDeptId).collect(Collectors.toList());
        List<SysDept> subDepts = findAllAndSubDept(parentIds);
        subDepts.addAll(result.getRecords());
        //转换为树形结构
        List<DeptTreeVo> deptTreeList = getDeptTree(subDepts);
        pageParam.setData(deptTreeList);
        pageParam.setTotalCount(result.getTotal());
        pageParam.setTotalPage(result.getPages());
        return pageParam;
    }

    /**
     * 获取部门树形列表
     *
     * @return 查询数据
     */
    @Override
    public List<SimpleTreeVo> getTreeList() {
        List<SysDept> sysDepts = this.list(Wrappers.<SysDept>lambdaQuery()
                .eq(SysDept::getDelFlag, DeleteFlagEnum.NOT_DELETE.getCode()));
        return getSimpleTree(sysDepts);
    }

    /**
     * 查询当前部门以及下级部门信息
     *
     * @param deptIds
     * @return
     */
    public List<SysDept> findAllAndSubDept(List<Integer> deptIds) {
        if (deptIds.isEmpty()) {
            return Collections.emptyList();
        }
        List<SysDept> depts = getBySubDept(deptIds);

        List<Integer> subDeptIds = depts.stream().map(SysDept::getDeptId)
                .collect(Collectors.toList());
        if (subDeptIds.isEmpty()) {
            return depts;
        }
        depts.addAll(findAllAndSubDept(subDeptIds));
        return depts;
    }

    public List<SysDept> getBySubDept(List<Integer> ids) {
        if (ids.isEmpty()) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<SysDept> queryWrapper = Wrappers.<SysDept>lambdaQuery()
                .in(SysDept::getParentId, ids);
        return this.list(queryWrapper);
    }

    /**
     * 构建部门树
     *
     * @param deptList 部门列表
     * @return 部门树形结构
     */
    private List<DeptTreeVo> getDeptTree(List<SysDept> deptList) {
        List<DeptTreeVo> treeList = deptList.stream()
                .filter(dept -> !dept.getDeptId().equals(dept.getParentId()))
                .map(dept -> {
                    DeptTreeVo node = new DeptTreeVo();
                    node.setId(dept.getDeptId());
                    node.setParentId(dept.getParentId());
                    node.setName(dept.getName());
                    node.setSort(dept.getSort());
                    node.setCreateTime(dept.getCreateTime());
                    return node;
                }).collect(Collectors.toList());
        return TreeUtil.buildByLoop(treeList, CommonConstants.TREE_PARENT_TOP_ID);
    }

    /**
     * 构建部门简单树
     *
     * @param deptList 部门列表
     * @return 部门简单树树形结构
     */
    private List<SimpleTreeVo> getSimpleTree(List<SysDept> deptList) {
        List<SimpleTreeVo> treeList = deptList.stream()
                .filter(dept -> !dept.getDeptId().equals(dept.getParentId()))
                .map(dept -> {
                    SimpleTreeVo node = new SimpleTreeVo();
                    node.setId(dept.getDeptId());
                    node.setParentId(dept.getParentId());
                    node.setKey(dept.getDeptId().toString());
                    node.setTitle(dept.getName());
                    node.setValue(dept.getDeptId().toString());
                    return node;
                }).collect(Collectors.toList());
        return TreeUtil.buildByLoop(treeList, CommonConstants.TREE_PARENT_TOP_ID);
    }
}
